import { findGrade } from "../../api/score";

Page({
  data: {
    terms: [], // 学期列表
    score:[{ scoreInfo: '无' }], // 成绩列表
  },

  onLoad: function() {
    this.calculateTerms();
  },

  calculateTerms: function() {
    const enrollmentDate = new Date('2021-09-01'); // 学生入学日期
    const today = new Date(); // 当前日期
    let terms = [];
    let startYear = enrollmentDate.getFullYear(); // 入学年份
    let month = enrollmentDate.getMonth() + 1; // 获取入学月份

    let currentTermStart = new Date(enrollmentDate); // 当前学期开始日期

    // 计算学期
    while (currentTermStart <= today) {
      let semesterYear = startYear;
      let termType = '上学期';
      if (month >= 3&&month <= 8) {
        termType = '下学期';
      }

      let semester = `${semesterYear}-${semesterYear + 1}${termType}`;
      terms.push(semester);

      // 更新到下一个学期
      if (termType === '上学期') {
        // 上学期结束后进入下学期
        currentTermStart.setMonth((currentTermStart.getMonth() + 6)%12);
      } else {
        // 下学期结束后进入下一个学年的上学期
        currentTermStart.setFullYear(currentTermStart.getFullYear() + 1);
        currentTermStart.setMonth(8); // 9月
        startYear++; // 年份增加
      }

      // 更新年份和月份
      startYear = currentTermStart.getFullYear();
      month = currentTermStart.getMonth() + 1;

      // 检查是否超过当前日期
      if (currentTermStart > today) {
        break;
      }
    }

    this.setData({ terms: terms });
  },

  extractAndFormatTerm:function(semesterString) {
    // 使用正则表达式匹配年份和学期
    const regex = /^(\d{4})-(\d{4})(上|下)学期$/;
    const match = semesterString.match(regex);
  
    if (match) {
      // 提取第一个年份和学期
      const firstYear = match[1];
      const term = match[3] === '上' ? '上' : '下';
  
      // 组合成新的字符串
      return `${firstYear}年${term}半学期`;
    }
  },

  selectTerm: function(e) {
    const userID = wx.getStorageSync('userID');
    const selectedTerm=this.extractAndFormatTerm(e.currentTarget.dataset.term);

    findGrade(userID, selectedTerm).then((res) => {
      wx.showToast({
        title: res.msg,
        icon:'none'
      });
      if (res.data==null) {
        this.setData({ score: [{ scoreInfo: '无' }] });
      }
      else{
        const processedData = res.data.map(item => {
          return {
            ...item,
            scoreInfo: `${item.courseName}  :${item.score}`
          };
        });
        // 将处理后的数据设置到页面的data中
        this.setData({ score: processedData });
      }
    });
  },
});